import { ElMessageBox } from 'element-plus'
import {
  checkModuleApi,
  createModuleApi,
  createPreviewComApi,
  getCodeConfigApi
} from '../api'
import { useRouter } from 'vue-router'
import { Session } from '/@/utils/storage'
import type { CreateCodeConfigParams, Store } from '../types'

export const useHandler = (store: Store) => {
  const router = useRouter()
  const init = async () => {
    store.loading = true
    const res = await getCodeConfigApi()
    store.codeConfig = res.data.codeConfig
    store.apis = res.data.apis
    store.loading = false
  }
  const validate = () => {
    return Promise.all([
      store.basicFormRef?.validate(),
      store.apiFormRef?.validate(),
      store.listPageFormRef?.validate()
    ])
  }

  const getConfig = (): CreateCodeConfigParams => {
    return {
      basicConfig: store.basicFormData,
      apiConfig: store.apiFormData,
      listPageConfig: store.listPageFormData
    }
  }

  const onPreview = async () => {
    try {
      store.loading = true
      await validate()
      const params = getConfig()
      Session.set('csdevCodeFormData', params)
      await createPreviewComApi(params)
      window.location.reload()
    } catch {}

    store.loading = false
  }

  const createModuleHandler = async () => {
    const base = router.options.history.base || '/'
    store.loading = true
    const params = getConfig()
    await createModuleApi(params)
    store.loading = false
    // Session.remove('csdevCodeFormData')
    // debugger
    window.open(`${base}${params.basicConfig.modulePath}`)
    setTimeout(() => {
      window.location.reload()
    }, 1000)
  }

  const onCreateModule = async () => {
    try {
      await validate()
      const res = await checkModuleApi(store.basicFormData.modulePath)
      if (res.data.exists) {
        ElMessageBox({
          title: '确认操作',
          message: '模块已存在是否覆盖？'
        }).then(createModuleHandler)
        return
      } else {
        createModuleHandler()
      }
    } catch {}
  }

  return {
    init,
    onPreview,
    onCreateModule
  }
}
